package table

import (
	"fmt"
	"os"
	"playbook/ginsvr/src/orm"
	"playbook/ginsvr/src/source/gene"
	"playbook/ginsvr/src/source/read"
	"strings"
)

type TableField struct {
	Type   string
	Column string
}

type TableInfo struct {
	TableName   string
	TableIdType string
	TableIdName string
	TableFields []TableField
}

type ModelField struct {
	Column   string
	Type     string
	Property string
}
type Model struct {
	PackageName string
	TableName   string
	ModelName   string
	TableIdType string
	TableIdName string
	ModelFields []ModelField
}

func GenerateModel(tableInfo TableInfo) error {
	var model Model
	tableName := tableInfo.TableName
	model.TableName = tableName
	modelName := buildModelName(tableName)
	model.ModelName = modelName
	model.TableIdType = tableInfo.TableIdType
	model.TableIdName = tableInfo.TableIdName
	model.PackageName = buildPackageName()
	var modelFields []ModelField
	for _, tableField := range tableInfo.TableFields {
		var modelField ModelField
		var property string
		column := tableField.Column
		columnArray := strings.Split(column, "_")
		for index, c := range columnArray {
			if index == 0 {
				property = c
			} else {
				property = property + strings.ToUpper(c[:1]) + c[1:]
			}

		}
		modelField.Column = column
		modelField.Property = property
		modelField.Type = tableField.Type
		modelFields = append(modelFields, modelField)
	}
	model.ModelFields = modelFields

	fmt.Println(os.Getwd())

	srcpath := orm.GetGeneSrcDefine("model").Srcpath
	standardName := modelName + ".java"

	err := gene.GeneSrcByTpl("Model", srcpath, standardName, model)
	if err != nil {
		return err
	}
	//触发扫描
	localPath := orm.GetLocalPath("00001")
	read.ScanByPath(localPath.LocalPath + string(os.PathSeparator) + srcpath + string(os.PathSeparator) + modelName + ".java")
	return nil
}

func buildModelName(tableName string) string {
	var modelName string
	for _, c := range strings.Split(tableName, "_") {
		modelName = modelName + strings.ToUpper(c[:1]) + c[1:]
	}
	return modelName + "Model"
}

func buildPackageName() string {
	gsd := orm.GetGeneSrcDefine("model")
	var srcPath = gsd.Srcpath
	var packageName = srcPath[strings.Index(srcPath, "java")+5:]
	packageName = strings.ReplaceAll(packageName, "\\", ".")
	return packageName
}
